//
//  Message2TableViewController.m
//  享动
//
//  Created by 沈浩hh on 16/4/6.
//  Copyright © 2016年 HHUI. All rights reserved.
//

#import "Message2TableViewController.h"
#import "Message2TableViewCell.h"
#import "Message2Model.h"
#import "Message2ViewController.h"

@interface Message2TableViewController ()

@property (nonatomic, strong) NSMutableArray *modelArray;
@property (nonatomic, strong) NSMutableArray *htmlArray;
// 下拉加载更多
@property (nonatomic, assign)NSInteger page;

@property (nonatomic, strong) FMDatabase *db;

// 接收存到数据库中的array来防止添加重复的
@property (nonatomic, strong) NSMutableArray *modelArrayTemp;

@end

@implementation Message2TableViewController

- (void)loadData:(NSInteger)subject_id
{
    // 在数据持久化之前要将表里的数据清除 防止反复写入
    [_db executeUpdate:@"DELETE FROM PersonList "];
    _page = 1;
    _modelArray = [NSMutableArray array];
    _htmlArray = [NSMutableArray array];
    NSDictionary *parDic = @{@"page" : [NSString stringWithFormat:@"%ld", (long)_page], @"pagesize" : @10, @"subject_id" : [NSString stringWithFormat:@"%ld", (long)subject_id]};
    [RequestManager requestWithUrl:@"http://media.api.thejoyrun.com/article-list-v1" requestType:RequestTypePost parDic:parDic finish:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        NSArray *dataArray = dic[@"data"];
  
        
        for (NSDictionary *dataDic in dataArray) {
            Message2Model *model = [[Message2Model alloc]init];
            [model setValuesForKeysWithDictionary:dataDic];
            [_modelArray addObject:model];
            [_htmlArray addObject:model.article_url];
            
            [_db executeUpdate:@"INSERT INTO PersonList (cover_img, article_url,sub_title,title,view_cnt) VALUES (?,?,?,?,?)", model.cover_img, model.article_url, model.sub_title, model.title, model.view_cnt];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView.mj_header endRefreshing];

            [self.tableView reloadData];
        });
    } error:^(NSError *error) {
        NSLog(@"错误2");
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    self.tableView.rowHeight = KHEIGHT / 2 / 3;
    
    [self.tableView registerNib:[UINib nibWithNibName:@"Message2TableViewCell" bundle:nil] forCellReuseIdentifier:@"Message2TableViewCell"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
}

- (void)noNetwork:(NSInteger)subject_id
{
   
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:[NSString stringWithFormat:@"Message%ld.db", subject_id]];
    
    _db = [FMDatabase databaseWithPath:path];
//    NSLog(@"____%@", path);
    if (![_db open]) {
        NSLog(@"不能打开数据库");
    }
    [_db executeUpdate:@"CREATE TABLE PersonList (cover_img text, article_url text,sub_title text,title text,view_cnt text)"];
    
    _modelArray = [NSMutableArray array];
    _modelArrayTemp = [NSMutableArray array];
    _htmlArray = [NSMutableArray array];
    FMResultSet *rs = [_db executeQuery:@"SELECT * FROM PersonList"];
    while ([rs next]) {
        NSString *cover_img = [rs stringForColumn:@"cover_img"];
        NSString *article_url = [rs stringForColumn:@"article_url"];
        NSString *sub_title = [rs stringForColumn:@"sub_title"];
        NSString *title = [rs stringForColumn:@"title"];
        NSString *view_cnt = [rs stringForColumn:@"view_cnt"];
        Message2Model *model = [[Message2Model alloc]init];
        model.cover_img = cover_img;
        model.article_url = article_url;
        model.sub_title = sub_title;
        model.title = title;
        model.view_cnt = view_cnt;
        [_modelArrayTemp addObject:model];
        [_modelArray addObject:model];
        [_htmlArray addObject:model.article_url];
    }
//    NSLog(@"11111 -=== %@" ,_modelArrayTemp);
//    NSLog(@"22222 ==== %@", _modelArray);
//    NSLog(@"33 ==== %@", _htmlArray);
    [rs close];
    
    
    
    
}


#pragma mark ---- 加载更多 -----
- (void)loadMoreData:(NSInteger)subject_id
{
    _page += 1;
    NSDictionary *parDic = @{@"page" :  [NSString stringWithFormat:@"%ld", (long)_page], @"pagesize" : @10, @"subject_id" : [NSString stringWithFormat:@"%ld", (long)subject_id]};
    [RequestManager requestWithUrl:@"http://media.api.thejoyrun.com/article-list-v1" requestType:RequestTypePost parDic:parDic finish:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        NSArray *dataArray = dic[@"data"];
        
        for (NSDictionary *dataDic in dataArray) {
            Message2Model *model = [[Message2Model alloc]init];
            [model setValuesForKeysWithDictionary:dataDic];
            [_modelArray addObject:model];
            [_htmlArray addObject:model.article_url];
        }
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            // 请求结束之后结束刷新 (不写的话只刷新一次)
            [self.tableView.mj_footer endRefreshing];
            [self.tableView reloadData];
        });
    } error:^(NSError *error) {
        NSLog(@"错误");
    }];
    
}

#pragma mark ---- 传参数用来网路解析 ----
- (void)setSubject_id:(NSInteger)subject_id
{
    NSLog(@"%ld", subject_id);
    [self noNetwork:subject_id];
    // 判断有没有网络
    if ([[NetWorkState shareInstance]reachability]) {
        // 数据请求
        [self loadData:subject_id];
    }
  
    // 上拉加载更多
    self.tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        // 加载更多
        [self loadMoreData:subject_id];
    }];
    
    // 下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader  headerWithRefreshingBlock:^{
        
        [self loadData:subject_id];
    }];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return _modelArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    Message2TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Message2TableViewCell" forIndexPath:indexPath];
    cell.model = _modelArray[indexPath.row];

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    Message2ViewController *messageVc = [[Message2ViewController alloc]init];
    messageVc.htmlStr = _htmlArray[indexPath.row];
    self.nav.tabBarController.tabBar.hidden = YES;

    [self.nav pushViewController:messageVc animated:YES];
}

- (void)viewWillAppear:(BOOL)animated
{
    self.nav.tabBarController.tabBar.hidden = NO;

}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
